<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import {
  ref,
  nextTick,
  onMounted,
  inject,
  watch,
  onActivated,
  reactive,
  computed,
} from "vue";
import { useStore } from "vuex";
import useTalk from "@/hook/talk.ts";
import ids from "virtual:svg-icons-names";
import { ImagePreview } from "vant";
const store = useStore();
const router = useRouter();
let route = useRoute();
let message = ref("");
let message_buttom = ref();
let socket: any = inject("socket");
let online: [] = store.state.online;

let userName = ref(undefined);

onActivated(() => {
  userName.value = route.query.userName;
});

const messageData = computed(() => {
  if (userName.value === undefined) return;
  if (store.state.msg[userName.value]) {
    return store.state.msg[userName.value];
  } else {
    store.commit("setMsg", { from: userName.value, msg: undefined });
    return store.state.msg[userName.value];
  }
});

watch(
  () => store.state.msg,
  () => {
    nextTick(() => {
      message_buttom.value.scrollIntoView();
    });
  },
  { deep: true }
);

function keydown() {
  if (!message.value.length) return;
  socket.socket.emit("exchange", {
    to: userName.value,
    msg: message.value,
  });

  store.commit("setMsg", {
    from: userName.value,
    msg: message.value,
    isSelf: true,
  });

  // messageData.push({
  //   time: Date.now().toString(),
  //   msg: message.value,
  //   isSelf: 1,
  // });
  message.value = "";
  nextTick(() => {
    message_buttom.value.scrollIntoView();
  });
}

let isVoice = ref(true);
function voiceHandle() {
  isVoice.value = !isVoice.value;
}

let { size, isTalk, cancelSend, startTalk, endTalk, touchmove } = useTalk();

const uploader = ref("uploader");

const afterRead = (file: { content: string }) => {
  let type: string = file.content.substring(0, 10).split(":")[1];
  socket.socket.emit("exchange", {
    to: userName.value,
    msg: {
      type,
      blob: file.content,
    },
  });
  store.commit("setMsg", {
    from: userName.value,
    msg: {
      type,
      blob: file.content,
    },
    isSelf: true,
  });
};

// 选择图片
// function addImgHandle() {
//   uploader.value.chooseFile();
// }

// 预览图片
function previewHandle(item: { msg: string }) {
  let images: Array<string> = [];
  messageData.forEach((res: { type: string; msg: string }) => {
    if (res.type === "image") {
      images.push(res.msg);
    }
  });

  let startPosition = images.findIndex((res) => res === item.msg);

  ImagePreview({
    images,
    startPosition,
  });
}

const showPopover = ref(false);

const accept = ref("");
// 通过 actions 属性来定义菜单选项
const actions = [
  { text: "图片", type: "image", icon: "photo-o" },
  { text: "视频", type: "video", icon: "video-o" },
];

const onSelect = ({ type }) => {
  accept.value = type + "/*";
  nextTick(() => {
    uploader.value.chooseFile();
  });
};

// 图标
const showIcons = ref(false);
function clickIcon(item: any) {
  const type = "icon";
  socket.socket.emit("exchange", {
    to: userName.value,
    msg: {
      type,
      blob: item,
    },
  });
  store.commit("setMsg", {
    from: userName.value,
    msg: {
      type,
      blob: item,
    },
    isSelf: true,
  });
  showIcons.value = false;
}

onMounted(() => {
  message_buttom.value.scrollIntoView();
});
</script>

<template>
  <div id="im">
    <van-nav-bar left-arrow :title="userName" @click-left="router.go(-1)">
      <template #left>
        <van-icon name="arrow-left" size="22px" />
      </template>
      <template #right>
        <van-icon name="ellipsis" size="22px" />
      </template>
    </van-nav-bar>
    <div class="content">
      <ul>
        <li
          class="messageBox"
          :class="item.isSelf ? 'R' : ''"
          v-for="(item, index) in messageData"
          :key="index"
        >
          <van-image
            class="headPortrait"
            fit="cover"
            radius="5"
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <van-image
            class="img"
            fit="cover"
            position="top"
            v-if="item.type == 'image'"
            :src="item.msg"
            @click="previewHandle(item)"
          />
          <video v-else-if="item.type == 'video'" :src="item.msg" controls>
            您的浏览器不支持 video 标签。
          </video>

          <div class="message" v-else>
            <audio
              controls
              class="audio-player"
              :src="item.msg"
              v-if="item.type == 'rec'"
            ></audio>
            <SvgIcon
              v-else-if="item.type === 'icon'"
              :name="item.msg"
              class="icon-item"
            ></SvgIcon>
            <div v-else>{{ item.msg }}</div>
          </div>
        </li>
        <li ref="message_buttom"></li>
        <!-- <li class="messageBox R">
          <van-image
            fit="cover"
            radius="5"
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <div class="message">hc</div>
        </li> -->
      </ul>
    </div>
    <div class="van-safe-area-bottom buttom van-hairline--top">
      <van-icon
        :name="isVoice ? 'phone-circle-o' : 'comment-circle-o'"
        @click="voiceHandle"
      />
      <van-field
        v-if="isVoice"
        class="input"
        v-model="message"
        rows="1"
        @keydown.enter="keydown"
      />
      <van-button
        v-else
        class="input button"
        @touchstart.stop="startTalk"
        @touchend.prevent.stop="endTalk"
        @touchmove.prevent="touchmove"
        >按住 说话</van-button
      >
      <van-popover v-model:show="showIcons" placement="top-end">
        <van-grid square clickable :border="false" column-num="4">
          <van-grid-item
            v-for="(item, index) in ids"
            :key="index"
            @click="clickIcon(item)"
          >
            <SvgIcon :name="item" class="icon-item"></SvgIcon>
          </van-grid-item>
        </van-grid>
        <template #reference>
          <van-icon name="smile-o" />
        </template>
      </van-popover>

      <van-popover
        v-model:show="showPopover"
        :actions="actions"
        placement="left-end"
        @select="onSelect"
      >
        <template #reference>
          <van-icon name="add-o" />
        </template>
      </van-popover>
    </div>
  </div>

  <van-uploader
    ref="uploader"
    :accept="accept"
    :after-read="afterRead"
    v-show="false"
  />

  <teleport to="#im">
    <transition name="van-fade">
      <div class="voice" v-show="isTalk">
        <van-icon name="volume-o" v-show="!cancelSend" />
        <ul v-show="!cancelSend">
          <li v-for="item in size" :style="item" class="item li1"></li>
        </ul>
        <van-icon name="revoke" v-show="cancelSend" />
      </div>
    </transition>
  </teleport>
</template>

<style scoped lang="scss">

.van-icon {
  color: var(--van-black);
}

::v-deep .van-nav-bar__content {
  height: 92px;
}

::v-deep .content {
  height: calc(100vh - 92px - 100px);
  overflow-y: auto;
  padding:20px;
  .messageBox{
    display:flex;
    margin: 0;
    padding: 0;
    margin: 15px 0;
    .headPortrait{
      width: 80px;
      height: 80px;
    }    
    .img {
      max-width: 350px;
      max-height: 500px;
      margin-left: 20px;
    }
    video{
      max-width: 350px;
      max-height: 500px;
      margin-left: 20px;
    }
    .message{
      box-sizing: border-box;
      background-color:#fff;
      position: relative;
      min-height: 80px;
      min-width: 80px;
      max-width: 600px;
      word-wrap: break-word;
      font-size: 28px;
      line-height: 1.5;
      margin-left: 20px;
      border-radius:20px;
      padding: 19px 23px;
      .svg-icon{
        font-size: 100px;
      }
      &:before{
        content:'';
        position: absolute;
        width: 0;   
        height: 0;
        border-color: transparent;
        border-style: solid;
        border-width: var(--van-popover-arrow-size);
        left: 0;
        top: 50%;
        border-right-color: #fff;
        border-left-width: 0;
        transform: translate(-100%,-50%);
      }
    }
      audio{
        height: 48px;
        margin-top: 8px;
        max-width: 500px;
      }
    }
   .R{
     flex-direction: row-reverse;
     .img{
       margin-right: 20px;
     }
     video{
        margin-right: 20px;
     }
    .message{
        margin-left: 0;
        margin-right: 20px;
        background-color: #9eea6a;
        &:before{
            transform: translate(100%,-50%) rotate(180deg);
            left: unset;
            right: 0;
            border-right-color: #9eea6a;
        }
    }
    
    }
}

::v-deep .buttom {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-around;
//   padding:10px;
  .input{
    height: 70px;
    width: 70%;
  }
  .button{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none; 
  }
  .van-icon{
      font-size: 52px;
  }
  .van-field{
      padding: 10px 15px;
      border-radius: 8px;
  }
  .van-field__body{
      height: 100%;
  }

}

  .van-grid {
    width: 480px;
  }
::v-deep .voice{
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 300px;
  height: 300px;
  background-color: rgba(0,0,0,.5);
  border-radius: 20px;
  
  .van-icon-volume-o{
    color: white;
    font-size: 100px;
    margin-right: 20px;
  }
  li{
    // display: block;
    height: 18px;
    background-color: #fff;
    margin: 10px 0;
    &:nth-child(1){
      width: 60px;
    }
    &:nth-child(2){
      width: 50px;
    }
    &:nth-child(3){
      width: 40px;
    }
    &:nth-child(4){
      width: 30px;
    }
  }
  .van-icon-revoke{
    color: white;
    font-size: 150px;
  }
}
</style>
